package com.ttc.mBackupK16.BackupContacts;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.ttc.mBackupK16.R;
import com.ttc.mBackupK16.BackupStorage.DropBox;
import com.ttc.mBackupK16.BackupStorage.Email;
import com.ttc.mBackupK16.BackupStorage.SDCard;
import com.ttc.mBackupK16.BackupStorage.StorageObject;
import com.ttc.mBackupK16.BackupStorage.Webservice;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ContactsListActivity extends Activity implements OnClickListener{
	
	ContactList myContactList;
	Button btnBackupContacts, btnCancelContacts;
	CheckBox chBCheckAllContacts;
	ListView lstContacts;
	CustomListAdapter adapter;
	ContactsManager myContactsManager;
	TextView txtContactsNumber, txtContactsNumberChecked;
	StorageObject storageObject;
	ProgressDialog progressDialog;
	boolean isBackupSuccess = false;
	
	final Handler handler = new Handler();
	final Runnable mUpdateResultGetContacts = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			adapter = new CustomListAdapter(ContactsListActivity.this, R.id.lstContacts, myContactList.getContacts(), txtContactsNumberChecked);
			lstContacts.setAdapter(adapter);
			txtContactsNumber.setText("/" + lstContacts.getCount());
			progressDialog.dismiss();
		}
	};
	
	final Runnable mUpdateResultSaveFile = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			if(isBackupSuccess){
				Toast.makeText(ContactsListActivity.this, "Contacts backuped success!", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(ContactsListActivity.this, "Contacts backuped fail!", Toast.LENGTH_SHORT).show();
			}
			progressDialog.dismiss();
			
		}
	};
	
	public final static int SDCARD = 0;
	public final static int GMAIL = 1;
	public final static int DROPBOX = 2;
	public final static int MYSERVICE = 3;
	
	public final static int OVERRIDE = 0;
	public final static int INCREAMENTAL = 1;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contacts_list);
		
		btnBackupContacts = (Button)findViewById(R.id.btnBackupContacts);
		btnBackupContacts.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_btn_backup, 0, 0, 0);
		
		btnCancelContacts = (Button)findViewById(R.id.btnCancelContacts);
		btnCancelContacts.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_btn_back_home, 0, 0, 0);
		
		chBCheckAllContacts = (CheckBox)findViewById(R.id.chBCheckAllContacts);
		lstContacts = (ListView)findViewById(R.id.lstContacts);
		txtContactsNumber = (TextView) findViewById(R.id.txtContactsNumber);
		txtContactsNumberChecked = (TextView) findViewById(R.id.txtContactsNumberChecked);
		
		btnBackupContacts.setOnClickListener(this);
		btnCancelContacts.setOnClickListener(this);
		chBCheckAllContacts.setOnClickListener(this);

		Thread threadGetContacts = new Thread(){
			public void run() {
				
				myContactsManager = new ContactsManager();
				myContactsManager.setCr(ContactsListActivity.this.getContentResolver());
				myContactList = myContactsManager.getContactList();
				
				handler.post(mUpdateResultGetContacts);
			};
		};
		threadGetContacts.start();
		
		// Create and show ProgressDialog
		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("Getting contacts....");
		progressDialog.show();
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnBackupContacts:
			if(Integer.parseInt(txtContactsNumberChecked.getText().toString()) == 0){
				Toast.makeText(getBaseContext(), "No found any contact checked!", Toast.LENGTH_SHORT).show();
			}else{
				showStorageTypeDialog("Backup to ?", R.drawable.ic_default);
			}
			break;
		case R.id.btnCancelContacts:
			this.finish();
			break;
		case R.id.chBCheckAllContacts:
			for(int i = 0; i< myContactList.getContacts().size(); ++i){
				myContactList.getContacts().get(i).setChecked(chBCheckAllContacts.isChecked());
			}
			adapter.notifyDataSetChanged();
			if(chBCheckAllContacts.isChecked()){
				txtContactsNumberChecked.setText(lstContacts.getCount() + "");
				adapter.iNumItemChecked = lstContacts.getCount();
			}else{
				txtContactsNumberChecked.setText("0");
				adapter.iNumItemChecked = 0;
			}
			break;
		default:
			break;
		}
	}
	
	public StringBuilder convertContactsToJSon()
	{
		StringBuilder buiderJSon= new StringBuilder();
		GsonBuilder gSonBuider= new GsonBuilder();
		Gson gSon=gSonBuider.create();
		for(int i=0;i< myContactList.getContacts().size();i++)
		{
			if(myContactList.getContacts().get(i).isChecked()){
				try
				{
					buiderJSon.append(gSon.toJson(myContactList.getContacts().get(i)));
					Log.i("json",buiderJSon.toString());
				}
				catch(JsonParseException ex)
				{
					Toast.makeText(this, "Have Error to parse to Json", Toast.LENGTH_LONG);
				}
			}
		}
		
		return buiderJSon;
	}
	
	private void showStorageTypeDialog(String strTitle, int iIDIcon){
    	AlertDialog.Builder builder =  new AlertDialog.Builder(this);
		builder.setTitle(strTitle);
		if(iIDIcon != -1)
			builder.setIcon(iIDIcon);
		builder.setItems(R.array.storage, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				switch (which) {
				case SDCARD:
					storageObject = new SDCard();
					showBackupTypeDialog(storageObject, "Backup Type ?", R.drawable.ic_default);
					break;
				case GMAIL:
					storageObject = new Email();
					showBackupTypeDialog(storageObject, "Backup Type ?", R.drawable.ic_default);
					break;
				case DROPBOX:
					storageObject = new DropBox();
					showBackupTypeDialog(storageObject, "Backup Type ?", R.drawable.ic_default);
					break;
				case MYSERVICE:
					storageObject = new Webservice();
					showBackupTypeDialog(storageObject, "Backup Type ?", R.drawable.ic_default);
					break;
				default:
					storageObject = null;
					break;
				}
				dialog.dismiss();
			}
		});
		builder.show();
    }
	
	private void showBackupTypeDialog(StorageObject storageObject, String strTitle, int iIDIcon){
    	AlertDialog.Builder builder =  new AlertDialog.Builder(this);
		builder.setTitle(strTitle);
		if(iIDIcon != -1)
			builder.setIcon(iIDIcon);
		builder.setItems(R.array.backupType, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				switch (which) {
				case OVERRIDE:
					showFileNameDialog();
					break;
				case INCREAMENTAL:
					break;
					
				default:
					break;
				}
				dialog.dismiss();
			}
		});
		builder.show();
    }
	
	public void showFileNameDialog() {
		final Dialog dialog = new Dialog(this, R.style.WideDialogTheme);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setContentView(R.layout.i_custom_dialog);
		dialog.setTitle("Enter Backup file name");
		final EditText txtContent = (EditText) dialog
				.findViewById(R.id.i_custom_dialog_txtContent);

		Button btnOk = (Button) dialog.findViewById(R.id.i_custom_dialog_btnOK);
		Button btnCancel = (Button) dialog
				.findViewById(R.id.i_custom_dialog_btnCancel);

		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});

		btnOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {			
				Thread threadSaveContacts = new Thread(){
					public void run() {			
						String backupFileName = txtContent.getText().toString();
						StringBuilder strJsonContacts = convertContactsToJSon();
						isBackupSuccess = storageObject.saveFile(strJsonContacts, "/mBackup/Contacts/" + backupFileName + ".json");
						handler.post(mUpdateResultSaveFile);
					};
				};
				threadSaveContacts.start();
				
				// Create and show ProgressDialog
				progressDialog = new ProgressDialog(ContactsListActivity.this);
				progressDialog.setMessage("Saving contacts file....");
				progressDialog.show();
				
				dialog.cancel();
			}
		});
		dialog.show();
	}
}
